package com.haochang.chunkvod.controller.activity.cash;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.basewin.define.InputPBOCInitData;
import com.haochang.base.BaseActivity;
import com.haochang.base.BaseEditText;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.HelperUtils;
import com.haochang.chunkvod.app.utils.SaleUtils;
import com.haochang.chunkvod.app.utils.TimeUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.app.utils.VodDialog;
import com.haochang.chunkvod.model.cash.CashData;
import com.haochang.chunkvod.model.cash.PrintEnum;
import com.haochang.chunkvod.model.cash.PrintInfo;
import com.haochang.chunkvod.model.cash.ThirdEnum;
import com.haochang.chunkvod.tools.thirdparty.zxing.view.CaptureActivity;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.tools.vod.thread.PrintThread;
import com.haochang.chunkvod.tools.vod.thread.ThreadPoolUtil;
import com.haochang.chunkvod.view.vod.dialog.DialogItemInfo;
import com.haochang.chunkvod.view.vod.dialog.KeyBoardDialog;
import com.haochang.chunkvod.view.vod.dialog.SingleSelectionDialog;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

/**
 *@author qintao
 *created at 2016/7/26 12:00
 * 结账
 */

public class CheckOutActivity extends BaseActivity implements KeyBoardDialog.KeyBoardOnSureListener
{
	private TitleView titleView;
	private BaseTextView tv_receivable, tv_received;
	private BaseTextView tv_change, tv_unreceived;
	private BaseTextView tv_checkOutRealTime;
	private RelativeLayout checkOutRealTime_div;
	private BaseTextView tv_coupons;//卷
	private RelativeLayout coupons_div;
	private BaseTextView tv_advanceReceive;//预收
	private RelativeLayout advanceReceive_div;
	private BaseTextView tv_receipt;//结账方式
	private RelativeLayout receipt_div;
	private LinearLayout pay_div;
	private RelativeLayout other_div;
	private BaseEditText et_cash, et_memberCard, et_thirdParty, et_public_comment_receivable, et_public_comment_receive;
	private BaseTextView tv_other_title, tv_other_content, tv_thirdParty;
	private CheckBox item_cb;
	private Button btn_checkOut, btn_order;
	private List<DialogItemInfo> checkOutTimeList = new ArrayList<DialogItemInfo>();//结账时间列表
	private List<DialogItemInfo> receiptModeList = new ArrayList<DialogItemInfo>();//收款方式列表
	private List<DialogItemInfo> thirdPayList = new ArrayList<DialogItemInfo>();//第三方支付方式列表
	private List<DialogItemInfo> reasonList = new ArrayList<DialogItemInfo>();//免单原因列表
	private String roomNum;
	private String billId;
	private String is_force_checkOut;//是否强制结账
	private int currentViewId = 0;
	private CashData cashData;
	private boolean isCheckOut = false;//是否结账
	private JSONObject prepay = null;
	private JSONObject currpay = null;
	private int received = 0;//实收
	private int pendPay = 0;//挂单
	private int receivable = 0;//应收
	private int preReceived = 0;//预收
	private String receivable_type = "normal";//结账类型
	private String reason = "";//原因
	private String timeType = "preTime";
	private String checktime = "";//结账时间
	private int unreceived;//未收
	private int cash, card, thirdParty;
	private String thirdType = ThirdEnum.ALI_PAY.getName();
	private String creditCustomerId = "";
	private String QR_code = "";
	private PrintEnum printEnum = PrintEnum.PRINT_CHECK_OUT;
	private JSONObject checkOutObject = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}

	@Override
	public void receiveParam()
	{
		roomNum = getIntent().getStringExtra(IntentKey.ROOM_NUM);
		is_force_checkOut = getIntent().getStringExtra(IntentKey.IS_FORCE_CHECKOUT);
		billId = getIntent().getStringExtra(IntentKey.BILL_ID);
		printEnum = (PrintEnum) getIntent().getSerializableExtra(IntentKey.CHECKOUT_TYPE);
	}

	@Override
	public void initData()
	{
		cashData = new CashData(CheckOutActivity.this);

		DialogItemInfo timeInfo1 = new DialogItemInfo("preTime", "预结时间", true);
		DialogItemInfo timeInfo2 = new DialogItemInfo("currTime", "当前时间", false);
		checkOutTimeList.add(timeInfo1);
		checkOutTimeList.add(timeInfo2);

		DialogItemInfo itemInfo1 = new DialogItemInfo("normal", "支付", true);
		receiptModeList.add(itemInfo1);

		DialogItemInfo info1 = new DialogItemInfo(ThirdEnum.ALI_PAY.getName(), "支付宝", true);
		DialogItemInfo info2 = new DialogItemInfo(ThirdEnum.WEI_XIN_PAY.getName(), "微信", false);
		DialogItemInfo info3 = new DialogItemInfo(ThirdEnum.CARD.getName(), "刷卡", false);
		thirdPayList.add(info1);
		thirdPayList.add(info2);
		thirdPayList.add(info3);
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_check_out);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(String.format("结账(%s)", roomNum)).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				billStatusRollBack();
			}

			@Override
			public void onDoneClick()
			{
				List<String> list = new ArrayList<String>();
				list.add("退出登录");
				int location[] = new int[2];
				ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
				img.getLocationOnScreen(location);
				int x = location[0];
				final VodPopWindow pop = new VodPopWindow(CheckOutActivity.this, list);
				pop.showPopupWindow(titleView, x);
				pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
				{
					@Override
					public void onSelectItem(int position)
					{
						switch (position)
						{
						case 0:
							loginOut();
							break;
						default:
							break;
						}
					}
				});
			}
		});
		tv_receivable = (BaseTextView) findViewById(R.id.tv_receivable);
		tv_received = (BaseTextView) findViewById(R.id.tv_received);
		tv_change = (BaseTextView) findViewById(R.id.tv_change);
		tv_unreceived = (BaseTextView) findViewById(R.id.tv_unreceived);
		tv_change.setText(String.format("找零："));
		tv_change.append(Html.fromHtml("<u>" + SaleUtils.getSaleString(pendPay) + "</u>"));
		tv_change.setOnClickListener(mOnBaseClickListener);
		checkOutRealTime_div = (RelativeLayout) findViewById(R.id.checkOutRealTime_div);
		tv_checkOutRealTime = (BaseTextView) findViewById(R.id.tv_checkOutRealTime);
		coupons_div = (RelativeLayout) findViewById(R.id.coupons_div);
		coupons_div.setOnClickListener(mOnBaseClickListener);
		tv_coupons = (BaseTextView) findViewById(R.id.tv_coupons);
		advanceReceive_div = (RelativeLayout) findViewById(R.id.advanceReceive_div);
		advanceReceive_div.setOnClickListener(mOnBaseClickListener);
		tv_advanceReceive = (BaseTextView) findViewById(R.id.tv_advanceReceive);
		receipt_div = (RelativeLayout) findViewById(R.id.receipt_div);
		receipt_div.setOnClickListener(mOnBaseClickListener);
		tv_receipt = (BaseTextView) findViewById(R.id.tv_receipt);
		pay_div = (LinearLayout) findViewById(R.id.pay_div);
		other_div = (RelativeLayout) findViewById(R.id.other_div);
		other_div.setOnClickListener(mOnBaseClickListener);
		et_cash = (BaseEditText) findViewById(R.id.et_cash);
		et_memberCard = (BaseEditText) findViewById(R.id.et_memberCard);
		et_thirdParty = (BaseEditText) findViewById(R.id.et_thirdParty);
		et_public_comment_receivable = (BaseEditText) findViewById(R.id.et_public_comment_receivable);
		et_public_comment_receive = (BaseEditText) findViewById(R.id.et_public_comment_receive);
		et_cash.addTextChangedListener(textWatcher);
		et_memberCard.addTextChangedListener(textWatcher);
		et_thirdParty.addTextChangedListener(textWatcher);
		et_public_comment_receivable.addTextChangedListener(textWatcher);
		et_public_comment_receive.addTextChangedListener(textWatcher);
		et_cash.setOnClickListener(mOnBaseClickListener);
		et_memberCard.setOnClickListener(mOnBaseClickListener);
		et_thirdParty.setOnClickListener(mOnBaseClickListener);
		et_public_comment_receive.setOnClickListener(mOnBaseClickListener);
		et_public_comment_receivable.setOnClickListener(mOnBaseClickListener);
		tv_thirdParty = (BaseTextView) findViewById(R.id.tv_thirdParty);
		tv_thirdParty.setOnClickListener(mOnBaseClickListener);
		tv_other_title = (BaseTextView) findViewById(R.id.tv_other_title);
		tv_other_content = (BaseTextView) findViewById(R.id.tv_other_content);
		item_cb = (CheckBox) findViewById(R.id.item_cb);
		item_cb.setChecked(true);
		btn_checkOut = (Button) findViewById(R.id.btn_checkOut);
		btn_order = (Button) findViewById(R.id.btn_order);
		btn_checkOut.setOnClickListener(mOnBaseClickListener);
		btn_order.setOnClickListener(mOnBaseClickListener);
		//		hideView();
		//		if (printEnum == PrintEnum.PRINT_CHECK_OUT)
		//		{
		//			cashData.requestCheckOutInfo(billId, new CashData.IPrintInfoListener()
		//			{
		//				@Override
		//				public void onRequestSuccess(JSONObject jsonObject)
		//				{
		//					checkOutObject = jsonObject;
		//				}
		//
		//				@Override
		//				public void onRequestFail(int errno, String errMsg)
		//				{
		//					ToastUtils.showText(CheckOutActivity.this, "获取结账列印信息失败");
		//				}
		//			});
		//		} else
		//		{
		//			cashData.requestPrintPrePayInfo(billId, new CashData.IPrintInfoListener()
		//			{
		//				@Override
		//				public void onRequestSuccess(JSONObject jsonObject)
		//				{
		//					checkOutObject = jsonObject;
		//				}
		//
		//				@Override
		//				public void onRequestFail(int errno, String errMsg)
		//				{
		//					ToastUtils.showText(CheckOutActivity.this, "获取列印基本信息失败");
		//				}
		//			});
		//		}
		//		cashData.requestCheckOutNum(billId, is_force_checkOut, new CashData.ICheckOutNumListener()
		//		{
		//			@Override
		//			public void onRequestSuccess(JSONObject jsonObject)
		//			{
		//				Logger.e(jsonObject.toString());
		//				JSONObject object = jsonObject.optJSONObject("consume");
		//				prepay = object.optJSONObject("prepay");
		//				if (prepay != null)
		//				{
		//					receivable = prepay.optInt("amount");
		//					checktime = prepay.optString("time");
		//					tv_receivable.setText(String.format("应收：%s", SaleUtils.getSaleString(receivable)));
		//					tv_checkOutRealTime.setText(TimeUtils.getMinutesString(checktime));
		//				}
		//				currpay = object.optJSONObject("currpay");
		//				preReceived = jsonObject.optInt("paied");
		//				tv_received.setText(String.format("实收：%s", SaleUtils.getSaleString(preReceived)));
		//				if (preReceived == 0 && pendPay == 0)
		//				{
		//					DialogItemInfo itemInfo2 = new DialogItemInfo("sign", "签单", false);
		//					DialogItemInfo itemInfo3 = new DialogItemInfo("free", "免单", false);
		//					DialogItemInfo itemInfo4 = new DialogItemInfo("fete", "招待", false);
		//					DialogItemInfo itemInfo5 = new DialogItemInfo("owe", "挂账", false);
		//					receiptModeList.add(itemInfo2);
		//					receiptModeList.add(itemInfo3);
		//					receiptModeList.add(itemInfo4);
		//					receiptModeList.add(itemInfo5);
		//				}
		//				unreceived = receivable + pendPay - preReceived;
		//				tv_unreceived.setText(Html.fromHtml("未收：" + "<font color=#f04e39>" + (unreceived > 0 ? SaleUtils.getSaleString(unreceived) : "0") + "</font>"));
		//			}
		//
		//			@Override
		//			public void onRequestFail(int errno, String errMsg)
		//			{
		//				ToastUtils.showText(CheckOutActivity.this, errMsg);
		//			}
		//		});
	}

	/**
	 * 桌台结账隐藏控件
	 */
	private void hideView()
	{
		checkOutRealTime_div.setVisibility(View.GONE);
		advanceReceive_div.setVisibility(View.GONE);
	}

	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.coupons_div:
				startEnterActivityForResult(CouponsDetailsActivity.class, IntentCode.CASH_COUPON);
				break;
			case R.id.advanceReceive_div:
				onPayForAnotherClick();
				break;
			case R.id.receipt_div:
				new SingleSelectionDialog.Builder(CheckOutActivity.this).dialogEnum(SingleSelectionDialog.DialogEnum.SPECIAL_PAY)
						.setTitle(R.string.receipt_mode).setSingleChoiceItems(receiptModeList, new SingleSelectionDialog.OnSelectListener()
						{
							@Override
							public void getValue(String code, String name)
							{
								showReceiptMode(code, name);
							}
						}).createDialog().show();
				break;
			case R.id.other_div:
				if (!CollectionUtils.isEmpty(reasonList))
					new SingleSelectionDialog.Builder(CheckOutActivity.this).setTitle(tv_other_title.getText().toString())
							.setSingleChoiceItems(reasonList, new SingleSelectionDialog.OnSelectListener()
							{
								@Override
								public void getValue(String code, String name)
								{
									if (!TextUtils.isEmpty(name))
									{
										if (receivable_type.equals("owe"))
										{
											creditCustomerId = code;
										}
										reason = name;
										tv_other_content.setText(reason);
									}
								}
							}).createDialog().show();
				break;
			case R.id.tv_thirdParty:
				new SingleSelectionDialog.Builder(CheckOutActivity.this).dialogEnum(SingleSelectionDialog.DialogEnum.PAY).setTitle(R.string.thirdPay)
						.setSingleChoiceItems(thirdPayList, new SingleSelectionDialog.OnSelectListener()
						{
							@Override
							public void getValue(String code, String name)
							{
								if (!TextUtils.isEmpty(name))
								{
									tv_thirdParty.setText(name);
									thirdType = code;
								}
							}
						}).createDialog().show();

				break;
			case R.id.btn_checkOut:
				checkOut();
				break;
			case R.id.btn_order:
				cashData.requestPreCheckOutInfo(billId, new CashData.IPrintInfoListener()
				{
					@Override
					public void onRequestSuccess(JSONObject jsonObject)
					{
						PrintInfo printInfo = new PrintInfo();
						printInfo.setType(PrintEnum.PRINT_PRE_CHECK_OUT.getName());
						printInfo.setContent(jsonObject.toString());
						ThreadPoolUtil.getInstanceSingleTaskExecutor().submit(new PrintThread(PrintEnum.PRINT_PRE_CHECK_OUT, printInfo));
					}

					@Override
					public void onRequestFail(int errno, String errMsg)
					{
						ToastUtils.showText(CheckOutActivity.this, "获取预结列印信息失败");
					}
				});
				break;
			case R.id.et_cash:
				currentViewId = R.id.et_cash;
				showKeyBoardDialog();
				break;
			case R.id.et_memberCard:
				ToastUtils.showText(CheckOutActivity.this, "暂未开发此功能");
				//				currentViewId = R.id.et_memberCard;
				//				showKeyBoardDialog();
				break;
			case R.id.et_thirdParty:
				currentViewId = R.id.et_thirdParty;
				showKeyBoardDialog();
				break;
			case R.id.tv_pend:
				Intent intent = new Intent(CheckOutActivity.this, PendDetailsActivity.class);
				startActivity(intent);
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 点击预付列表
	 */
	private void onPayForAnotherClick()
	{
		Intent intent = new Intent(CheckOutActivity.this, PayForAnotherActivity.class);
		intent.putExtra(IntentKey.CASH_PAY_TYPE, PayForAnotherActivity.PayEnum.PRE_PAY);
		startActivityForResult(intent, IntentCode.PAY_FOR_ANOTHER);
	}

	/**
	 * 自定义键盘输入
	 */
	private void showKeyBoardDialog()
	{
		KeyBoardDialog keyBoardDialog = new KeyBoardDialog(CheckOutActivity.this);
		keyBoardDialog.setKeyBoardOnSureListener(CheckOutActivity.this);
		keyBoardDialog.show();
	}

	@Override
	public void setValue(String value)
	{
		if (value.contains("."))
			ToastUtils.showText(CheckOutActivity.this, R.string.error_number);
		else if (value.length() > 9)
			ToastUtils.showText(CheckOutActivity.this, R.string.error_max_number);
		else
			switch (currentViewId)
			{
			case R.id.et_cash:
				et_cash.setText(value);
				break;
			case R.id.et_memberCard:
				et_memberCard.setText(value);
				break;
			case R.id.et_thirdParty:
				et_thirdParty.setText(value);
				break;
			default:
				break;
			}
	}

	@Override
	public void onBackPressed()
	{
		billStatusRollBack();
		super.onBackPressed();
	}

	/**
	 * 如果没有结账,返回首页的时候账单状态回滚
	 */
	private void billStatusRollBack()
	{
		if (!isCheckOut)
		{
			cashData.requestBillStatusRollBack(billId, new CashData.IBillStatusRollBackListener()
			{
				@Override
				public void onRequestSuccess()
				{
					finish();
				}
			});
		}
	}

	/**
	 * 二维码扫码
	 */
	private void scanQRCode()
	{
		Intent intent = new Intent();
		intent.setClass(CheckOutActivity.this, CaptureActivity.class);
		startActivityForResult(intent, IntentCode.QR_CODE_REQUEST);
	}

	/**
	 * 结算操作
	 */
	private void checkOut()
	{
		if (receivable_type.equals("normal"))
		{
			if (unreceived > 0)
			{
				ToastUtils.showText(CheckOutActivity.this, "还有未收金额，无法结算");
			} else
			{
				//执行结算,如果第三方支付金额大于0，且支付类型不为刷卡,进行扫码
				if (thirdParty > 0)
				{
					if (!thirdType.equals(ThirdEnum.CARD.getName()))
					{
						scanQRCode();
					} else
					{
						requestThirdCardPay();
					}
				} else
				{
					requestPay();
				}
			}
		} else
		{
			requestPay();
		}
	}

	private TextWatcher textWatcher = new TextWatcher()
	{
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after)
		{

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count)
		{

		}

		@Override
		public void afterTextChanged(Editable s)
		{
			cash = TextUtils.isEmpty(et_cash.getText().toString()) ? 0 : SaleUtils.getSaleInt(et_cash.getText().toString());
			card = TextUtils.isEmpty(et_memberCard.getText().toString()) ? 0 : SaleUtils.getSaleInt(et_memberCard.getText().toString());
			thirdParty = TextUtils.isEmpty(et_thirdParty.getText().toString()) ? 0 : SaleUtils.getSaleInt(et_thirdParty.getText().toString());
			received = cash + card + thirdParty + preReceived;
			unreceived = receivable + pendPay - received;
			tv_received.setText(String.format("实收：%s", SaleUtils.getSaleString(received)));
			tv_unreceived.setText(Html.fromHtml("未收：" + "<font color=#f04e39>" + (unreceived > 0 ? SaleUtils.getSaleString(unreceived) : "0") + "</font>"));
		}
	};

	/**
	 * 调用第三方pos机刷卡支付
	 */
	private void requestThirdCardPay()
	{
		try
		{
			Intent intent = new Intent();
			// 此处不设置金额，在下面PBOC流程中就需要设置
			int amt = Integer.parseInt("1");
			intent.putExtra(InputPBOCInitData.AMOUNT_FLAG, 1);
			intent.putExtra(InputPBOCInitData.USE_DEVICE_FLAG, InputPBOCInitData.USE_MAG_CARD | InputPBOCInitData.USE_RF_CARD | InputPBOCInitData.USE_IC_CARD);
			intent.putExtra(InputPBOCInitData.TIMEOUT, 60);
			try
			{
				//				ServiceManager.getInstence().getPboc().startTransfer(PBOCOption.ONLINE_PAY, intent, pboc_callback);
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 刷卡调用拉卡拉 请求支付 
	 */
	private void requestLaKaLaPay()
	{
		try
		{
			ComponentName component = new ComponentName("com.lkl.cloudpos.payment", "com.lkl.cloudpos.payment.activity.MainMenuActivity");
			Intent intent = new Intent();
			intent.setComponent(component);
			Bundle bundle = new Bundle();
			bundle.putString("msg_tp", "0200");
			bundle.putString("pay_tp", "0");
			bundle.putString("proc_tp", "00");
			bundle.putString("proc_cd", "000000");
			bundle.putString("amt", SaleUtils.getSaleString(thirdParty / 100));
			bundle.putString("order_no", billId);
			bundle.putString("appid", "com.haochang.chunkvod");
			bundle.putString("time_stamp", TimeUtils.getTimeStr());
			intent.putExtras(bundle);
			this.startActivityForResult(intent, IntentCode.LAKALA_REQUEST);
		} catch (ActivityNotFoundException e)
		{
			e.printStackTrace();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 后台请求支付
	 */
	private void requestPay()
	{
		JSONObject jsonObject = new JSONObject();
		try
		{
			jsonObject.put("cash", cash);
			jsonObject.put("third_pay_amount", thirdParty / 100);//thirdParty方便测试
			if (thirdParty > 0)
			{
				jsonObject.put("third_pay_method", thirdType);
				if (!TextUtils.isEmpty(QR_code))
					jsonObject.put("auth_code", QR_code);
			}
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
		Logger.e(jsonObject.toString());
		cashData.requestRoomCheckOut(billId, receivable_type, checktime, reason, creditCustomerId, jsonObject.toString(), new CashData.IRoomCheckOutListener()
		{
			@Override
			public void onRequestSuccess(JSONObject jsonObject)
			{
				ToastUtils.showText(CheckOutActivity.this, "收款成功");
				VodDialog.closeDialog(VodDialog.DialogEnum.LOADING_PAY);
				printCheckOutInfo();
				if (!jsonObject.isNull("refund"))
				{
					JSONObject object = jsonObject.optJSONObject("refund");
					int cash = object.optInt("cash");
					int alipay = object.optInt("alipay");
					int weixinpay = object.optInt("weixinpay");
					int card = object.optInt("card");
					StringBuffer sb = new StringBuffer();
					if (cash > 0)
						sb.append("现金：找零" + "<font color=#f04e39>" + SaleUtils.getSaleString(cash) + "</font>" + "元" + "<br />");
					if (alipay > 0)
						sb.append("支付宝：退款" + "<font color=#f04e39>" + SaleUtils.getSaleString(alipay) + "</font>" + "元" + "<br />");
					if (weixinpay > 0)
						sb.append("微信：退款" + "<font color=#f04e39>" + SaleUtils.getSaleString(weixinpay) + "</font>" + "元" + "<br />");
					if (card > 0)
						sb.append("刷卡：退款" + "<font color=#f04e39>" + SaleUtils.getSaleString(card) + "</font>" + "元" + "<br />");
					String tip = sb.toString();
					tip = tip.substring(0, tip.lastIndexOf("<br />"));
					if (!TextUtils.isEmpty(tip))
						new VodDialog.Builder(context).dialogEnum(VodDialog.DialogEnum.SINGLE_CUSTOM_VIEW).btnNegativeText(R.string.cancel)
								.btnNeutralText(R.string.sure).cancelableOnTouchOutside(false).cancelable(false).contentName(tip)
								.onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
								{
									@Override
									public void onOnlyCancelClick()
									{
										setResult(RESULT_OK, getIntent());
										finish();
									}

									@Override
									public void onOkClick()
									{
									}

									@Override
									public void onCancelClick()
									{
									}
								}).build().show();
				} else
				{
					setResult(RESULT_OK, getIntent());
					finish();
				}
			}

			@Override
			public void onRequestFail(int errno, String errMsg)
			{
				if (TextUtils.isEmpty(errMsg))
					ToastUtils.showText(CheckOutActivity.this, "收款失败");
				else
					ToastUtils.showText(CheckOutActivity.this, errMsg);
				VodDialog.closeDialog(VodDialog.DialogEnum.LOADING_PAY);
			}
		});
	}

	/**
	 * 结账成功后打印数据
	 */
	private void printCheckOutInfo()
	{
		//是否打印列印小票
		if (item_cb.isChecked())
		{
			if (printEnum == PrintEnum.PRINT_CHECK_OUT)
			{
				//结账
				if (checkOutObject != null)
				{
					try
					{
						if (cash > 0)
							checkOutObject.put("cash", cash);
						if (thirdParty > 0)
						{
							checkOutObject.put("thirdType", thirdType);
							checkOutObject.put("thirdParty", thirdParty);
						}
					} catch (JSONException e)
					{
						e.printStackTrace();
					}
					PrintInfo printInfo = new PrintInfo();
					printInfo.setType(PrintEnum.PRINT_CHECK_OUT.getName());
					printInfo.setContent(checkOutObject.toString());
					ThreadPoolUtil.getInstanceSingleTaskExecutor().submit(new PrintThread(PrintEnum.PRINT_CHECK_OUT, printInfo));
				} else
				{
					ToastUtils.showText(CheckOutActivity.this, "未获取到结账列印信息");
				}

			} else
			{
				//预买
				if (checkOutObject == null)
				{
					ToastUtils.showText(CheckOutActivity.this, "未获取到预付款列印信息");
					return;
				}
				try
				{
					if (cash > 0)
						checkOutObject.put("cash", cash);
					if (thirdParty > 0)
					{
						checkOutObject.put("thirdType", thirdType);
						checkOutObject.put("thirdParty", thirdParty);
					}
					checkOutObject.put("room_num", roomNum);
					checkOutObject.put("shop_name", HelperUtils.getHelperInstance().getSValue(IntentKey.SHOP_NAME, ""));
					checkOutObject.put("receive_device", HelperUtils.getHelperInstance().getSValue(IntentKey.DEVICE_NAME, ""));
					checkOutObject.put("staff_name", HelperUtils.getHelperInstance().getSValue(IntentKey.USERNAME, ""));
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
				PrintInfo printInfo = new PrintInfo();
				printInfo.setType(PrintEnum.PRINT_PRE_PAY.getName());
				printInfo.setContent(checkOutObject.toString());
				ThreadPoolUtil.getInstanceSingleTaskExecutor().submit(new PrintThread(PrintEnum.PRINT_PRE_PAY, printInfo));
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == IntentCode.SPECIAL_PAY_REQUEST && resultCode == RESULT_OK && data != null)
		{
			DialogItemInfo dialogItemInfo = (DialogItemInfo) data.getSerializableExtra(IntentKey.DIALOGITEMINFO);
			for (DialogItemInfo dialogItemInfo1 : receiptModeList)
			{
				if (dialogItemInfo.getCode().equals(dialogItemInfo1.getCode()))
				{
					dialogItemInfo1.setSelected(true);
				} else
				{
					dialogItemInfo1.setSelected(false);
				}
			}
			showReceiptMode(dialogItemInfo.getCode(), dialogItemInfo.getName());
		} else if (requestCode == IntentCode.LAKALA_REQUEST && resultCode == RESULT_OK)
		{
			//支付成功,把thirdParty支付金额设置成0
			Logger.e("支付成功");
			ToastUtils.showText(CheckOutActivity.this, "支付成功");
			thirdParty = 0;
			if (cash > 0)
			{
				requestPay();
			} else
			{
				setResult(RESULT_OK, getIntent());
				finish();
			}
		} else if (requestCode == IntentCode.LAKALA_REQUEST && resultCode == RESULT_CANCELED)
		{
			Logger.e("支付取消");
			Bundle bundle = data.getExtras();
			String reason = bundle.getString("reason");
			if (!TextUtils.isEmpty(reason))
			{
				ToastUtils.showText(CheckOutActivity.this, reason);
			}
		} else if (requestCode == IntentCode.LAKALA_REQUEST && resultCode == -2)
		{
			//交易失败
			Bundle bundle = data.getExtras();
			String reason = bundle.getString("reason");
			if (!TextUtils.isEmpty(reason))
			{
				ToastUtils.showText(CheckOutActivity.this, reason);
			}
		} else if (requestCode == IntentCode.QR_CODE_REQUEST && resultCode == RESULT_OK && data != null)
		{
			Bundle bundle = data.getExtras();
			QR_code = bundle.getString("result");
			if (TextUtils.isEmpty(QR_code))
			{
				ToastUtils.showText(CheckOutActivity.this, "二维码为空");
			} else
			{
				requestPay();
			}
		}
	}

	/**
	 * 显示不同支付方式下的样式
	 */
	private void showReceiptMode(String code, String name)
	{
		receivable_type = code;
		if (!TextUtils.isEmpty(name))
		{
			reason = "";
			tv_receipt.setText(name);
			if (name.equals("支付"))
			{
				pay_div.setVisibility(View.VISIBLE);
				other_div.setVisibility(View.GONE);
			} else
			{
				pay_div.setVisibility(View.GONE);
				other_div.setVisibility(View.VISIBLE);
				tv_other_title.setText(name.endsWith("挂账") ? name + "人" : name + "原因");
				tv_other_content.setText("");
			}
			if (code.equals("free") || code.equals("fete"))
			{
				String type;
				if (code.equals("free"))
					type = "0";
				else
					type = "1";
				cashData.requestReason(type, new CashData.IReasonListener()
				{
					@Override
					public void onRequestSuccess(List<DialogItemInfo> list)
					{
						if (!CollectionUtils.isEmpty(list))
						{
							reasonList.clear();
							reasonList.addAll(list);
							reason = reasonList.get(0).getName();
							tv_other_content.setText(reason);
						}
					}
				});
			} else if (code.equals("owe"))
			{
				cashData.requestCredit(new CashData.IReasonListener()
				{

					@Override
					public void onRequestSuccess(List<DialogItemInfo> list)
					{
						if (!CollectionUtils.isEmpty(list))
						{
							reasonList.clear();
							reasonList.addAll(list);
							reason = reasonList.get(0).getName();
							tv_other_content.setText(reason);
						}
					}
				});
			} else
			{
				reasonList.clear();
			}
		}
	}

}
